package com.itheima.interceptor;

import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
//登录校验拦截器
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求url
        StringBuffer requestURL = request.getRequestURL();
        log.info("url:{}", requestURL.toString());
        //2.判断url是否包含login(登录路径)，如果包含则放行
       if (requestURL.toString().contains("login")) {
           return true;
       }
        //3.获取请求头中的令牌（token）
        String token = request.getHeader("token");
        //4.判断令牌是否存在
        if (token == null) {
            log.warn("令牌不存在");
            response.setStatus(401);
            //不放行
            return false;
        }
        //5.解析token，如果解析失败则响应401
        Claims claims = JwtUtils.parseJWT(token);
        if (claims == null) {
            response.setStatus(401);
            return false;
        }
        //6.放行
        return true;
    }
}
